package com.agent.service.impl;

import com.agent.mapper.UserMapper;
import com.agent.entity.User;
import com.agent.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.agent.dto.LoginRequestDTO;
import com.agent.dto.RegisterRequestDTO;
import com.agent.dto.UpdateUserRequestDTO;
import com.agent.utils.JWTUtils;
import org.springframework.util.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 密码加密
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    // 登录
    @Override
    public String login(LoginRequestDTO req) {
        // 参数校验
        if (req == null || !StringUtils.hasText(req.getUsername()) || !StringUtils.hasText(req.getPassword())) {
            throw new IllegalArgumentException("用户名或密码为空！");
        }
        // 查询用户
        User user = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, req.getUsername())
                .eq(User::getDeleted, 0)
                .last("limit 1"));
        // 账号启禁用状态
        if (user == null || !Objects.equals(user.getStated(), 1)) {
            throw new IllegalArgumentException("用户状态不可用！");
        }
        // 密码校验
        if (!passwordEncoder.matches(req.getPassword(), user.getPassword())) {
            throw new IllegalArgumentException("用户密码错误！");
        }
        return JWTUtils.create(user.getId(), user.getUsername());
    }

    @Override
    public Long register(RegisterRequestDTO req) {
        // 参数校验
        if (req == null || !StringUtils.hasText(req.getUsername()) || !StringUtils.hasText(req.getPassword())) {
            throw new IllegalArgumentException("用户名或密码不能为空！");
        }
        // 用户名唯一
        long exists = count(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, req.getUsername())
                .eq(User::getDeleted, 0));
        if (exists > 0) {
            throw new IllegalArgumentException("用户已经存在！");
        }
        // 邮箱唯一
        if (StringUtils.hasText(req.getEmail())) {
            long emailExists = count(new LambdaQueryWrapper<User>()
                    .eq(User::getEmail, req.getEmail())
                    .eq(User::getDeleted, 0));
            if (emailExists > 0) {
                throw new IllegalArgumentException("邮箱已存在！");
            }
        }
        // 插入数据
        User user = User.builder()
                .username(req.getUsername())
                .password(passwordEncoder.encode(req.getPassword()))
                .email(req.getEmail())
                .stated(1)
                .deleted(0)
                .build();
        save(user);
        return user.getId();
    }

    @Override
    public User getUserInfo(Long id) {
        if (id == null) return null;
        User user = getById(id);
        if (user == null || Objects.equals(user.getDeleted(), 1)) return null;
        user.setPassword(null); // hide password
        return user;
    }

    @Override
    public boolean updateUser(Long currentUserId, UpdateUserRequestDTO req) {
        // 获得当前用户id
        if (currentUserId == null) {
            throw new IllegalArgumentException("Unauthorized");
        }
        Long targetId = req.getId() != null ? req.getId() : currentUserId;
        if (!currentUserId.equals(targetId)) {
            // For simplicity, only allow self-update
            throw new IllegalArgumentException("No permission to update others");
        }
        // 根据id查询用户
        User user = getById(targetId);
        if (user == null || Objects.equals(user.getDeleted(), 1)) {
            throw new IllegalArgumentException("用户不存在！");
        }
        // 目标用户名唯一性判断
        if (StringUtils.hasText(req.getUsername()) && !req.getUsername().equals(user.getUsername())) {
            long exists = count(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, req.getUsername())
                    .ne(User::getId, targetId)
                    .eq(User::getDeleted, 0));
            if (exists > 0) throw new IllegalArgumentException("用户名已存在");
            user.setUsername(req.getUsername());
        }
        // 目标邮箱唯一性判断
        if (StringUtils.hasText(req.getEmail()) && !Objects.equals(req.getEmail(), user.getEmail())) {
            long emailExists = count(new LambdaQueryWrapper<User>()
                    .eq(User::getEmail, req.getEmail())
                    .ne(User::getId, targetId)
                    .eq(User::getDeleted, 0));
            if (emailExists > 0) throw new IllegalArgumentException("Email already in use");
            user.setEmail(req.getEmail());
        }
        // 目标密码
        if (StringUtils.hasText(req.getPassword())) {
            user.setPassword(passwordEncoder.encode(req.getPassword()));
        }
        // 目标状态
        if (req.getStated() != null) {
            user.setStated(req.getStated());
        }
        // 更新
        return updateById(user);
    }
}
